package io.github.biezhi.elves.spider;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.model.CompImport;
import io.github.biezhi.elves.service.CompImportService;
import io.github.biezhi.elves.utils.StringUtils;
import io.github.biezhi.elves.utils.WebDriverUtils;

@Service
public class CompImportSpider {
	@Resource
	private CompImportService compImportService;
	private static CompImportService staticCompImportService;
	
	@Bean
	public CompImportService getCompImportServiceBean(){
		if(compImportService!=null){
			staticCompImportService = compImportService;
			return staticCompImportService;
		}
		return null;
	}
	
	/**
	 * 开始执行爬去百度拾取坐标系统更新企业导入表操作
	 * @throws Exception 
	 */
	static final int pageNo = 1;
	static int pageSize = 10;
	public void startCompImport() throws Exception{
		while(true){
//			pageNo++;
			baiduCompImportPointData(pageNo, pageSize);
		}
	}
	
	/**
	 * 通过百度拾取坐标系统获取某酒店/会所坐标数据信息
	 * @param pageNo		参数说明:页号
     * @param pageSize		参数说明:每页显示记录数
	 */
	static final Integer cityId = 1;
	static WebDriver driver;
	// 1、开启个浏览器并且输入链接
	static String url = "http://api.map.baidu.com/lbsapi/getpoint/index.html";
	private void baiduCompImportPointData(int pageNo, int pageSize) throws Exception{
		boolean isNull = false;
		List<CompImport> existDataList = new ArrayList<CompImport>();
		List<CompImport> nullDataList = new ArrayList<CompImport>();
		
		//查询还没爬取企业导入表数据
		int countDataNotIsLoad = compImportService.countCompImportDataForLngAndLatNotZero(cityId);
		if(countDataNotIsLoad==0){
			isNull = true;
		}
		//分页查询爬取企业导入表经纬度为0的数据
		List<CompImport> compImportPageList = compImportService.queryCompImportDataPage(pageNo, pageSize, cityId);
		if(compImportPageList!=null && compImportPageList.size()>0){
			//当前要爬取数据不足最大记录数时,则取当前要爬取的数据量
			if(compImportPageList.size()<pageSize){
				pageSize = compImportPageList.size();
			}
			for(CompImport compImport : compImportPageList){
				CompImport existData = new CompImport();
				CompImport nullData = new CompImport();
				
				boolean isKillChrome = false;
				//检测程序
				if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
					//检测并杀掉程序
					StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME);
					isKillChrome = true;
				}
				
				if(!isKillChrome) {
					//如果没有发现chrome浏览器进程以及chromedriver驱动，则重置isKillChrome标识为true
					if(!StringUtils.findProcess(Constants.CHROME_PROCESS_NAME) && !StringUtils.findAndKillProcess(Constants.CHROME_DRIVER_PROCESS_NAME)){
						isKillChrome = true;
					}
				}
				
				if(driver==null || isKillChrome){
					WebDriver driver1 = WebDriverUtils.getChromeDriver(url);
					driver = driver1;
				}else{
					driver.get(url);
				}

				Integer cityId = compImport.getCityId();
				String compName = compImport.getCompName();
				System.out.println("地市ID{{}}==>" + cityId + "，企业名称{{}}==>" + compName);
				
				// 2、向百度拾取坐标系统输入框输入需要查询的值
				WebDriverUtils.inputStrByJS(driver, "localvalue", compName);
				
				// 3、点击百度拾取坐标系统[更换城市]
				JavascriptExecutor js = (JavascriptExecutor) driver;
		        js.executeScript("showPop()");

		        // 休息5秒，加载数据
		 		try {
		 			Thread.sleep(5000);
		 		} catch (InterruptedException e) {
		 			e.printStackTrace();
		 		}
		 		
		 		// 4、修改百度拾取坐标系统[更换城市]的值
		 		//广州
				if(cityId == 1){
			 		WebElement changeCityElement = driver.findElement(By.xpath("//*[@id=\"selCity\"]/tbody/tr[6]/td[2]/nobr[1]/a"));
			 		WebDriverUtils.scrollToElementAndClick(changeCityElement, driver);
				}else if(cityId == 2){
					//深圳
					WebElement changeCityElement = driver.findElement(By.xpath("//*[@id=\"selCity\"]/tbody/tr[6]/td[2]/nobr[15]/a"));
			 		WebDriverUtils.scrollToElementAndClick(changeCityElement, driver);
				}
				
				 // 休息5秒，加载数据
		 		try {
		 			Thread.sleep(5000);
		 		} catch (InterruptedException e) {
		 			e.printStackTrace();
		 		}
		 		
				// 5、得到百度一下的按钮
				WebElement submitElement = driver.findElement(By.id("localsearch"));
		
				// 6、点击百度一下
				WebDriverUtils.scrollToElementAndClick(submitElement, driver);
		
				// 休息5秒，加载数据
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				// 7、右侧地图Info中div的 id 为 MapInfo 的 div 下面的所有 div
				List<WebElement> divElements = driver.findElements(By.cssSelector("#MapInfo > #txtPanel > ul"));
				
				if(divElements!=null && divElements.size()>0){
					for(int i = 0; i<divElements.size(); i++){
						// 8、找到搜索的第一个链接
						try{
							WebElement aElement = divElements.get(i).findElement(By.cssSelector("li > div > a"));
							if(aElement!=null){
								String textName = aElement.getText();
								if(textName.equals(compImport.getCompName())){
									System.out.println("textName{{}}==>" + textName);
									existData.setCityId(cityId);
									existData.setCompName(textName);
								}else{
									System.out.println("compName{{}}==>" + compName);
//									hotelInfo.setBaiduHotelName(textName);
									
									if(isNull){
										existData.setCityId(cityId);
										existData.setCompName(compName);
										existDataList.add(existData);
									}else{
										nullData.setCityId(cityId);
										nullData.setCompName(compName);
										nullDataList.add(nullData);
										continue;
									}
								}
							}else{
								System.err.println("没有匹配到数据!!!");
							}
						}catch(Exception e){
							System.err.println("aElement进入catch异常,没有匹配到数据,把企业名称【" + compName + "】放到nullDataList集合里面去{{}}==>");
							String resultCont = driver.findElement(By.cssSelector("#MapInfo > #txtPanel")).getText();
							System.err.println(resultCont);
//							compImportUpdate.setResultCont(resultCont);
							if(isNull){
								existData.setCityId(cityId);
								existData.setCompName(compName);
								existDataList.add(existData);
							}else{
								nullData.setCityId(cityId);
								nullData.setCompName(compName);
								nullDataList.add(nullData);
							}
						}
						
						try{
							WebElement pElement = divElements.get(i).findElement(By.cssSelector("li > div > p"));
							if(pElement!=null){
								String splitStr1 = "：";
								String splitStr2 = ",";
								String pTextName = pElement.getText();
								String[] pTexts = pElement.getText().split("\n");
//								System.out.println(pTextName);
								
								if(pTexts[0].contains("电话" + splitStr1)){
									existData.setCompLng(pTexts[2].split(splitStr1)[1].split(splitStr2)[0]);
									existData.setCompLat(pTexts[2].split(splitStr1)[1].split(splitStr2)[1]);
									existDataList.add(existData);
									
									System.out.println("电话号码{{}}==>" + pTexts[1].split(splitStr1)[1]);
									System.out.println("横坐标{{}}==>" + pTexts[2].split(splitStr1)[1].split(splitStr2)[0]);
									System.out.println("纵坐标{{}}==>" + pTexts[2].split(splitStr1)[1].split(splitStr2)[1]);
								} else if(pTexts[0].contains("地址" + splitStr1)) {
									existData.setCompLng(pTexts[1].split(splitStr1)[1].split(splitStr2)[0]);
									existData.setCompLat(pTexts[1].split(splitStr1)[1].split(splitStr2)[1]);
									existDataList.add(existData);
								} else {
									existData.setCompLng(pTexts[2].split(splitStr1)[1].split(splitStr2)[0]);
									existData.setCompLat(pTexts[2].split(splitStr1)[1].split(splitStr2)[1]);
									existDataList.add(existData);
									
									System.out.println("横坐标{{}}==>" + pTexts[1].split(splitStr1)[1].split(splitStr2)[0]);
									System.out.println("纵坐标{{}}==>" + pTexts[1].split(splitStr1)[1].split(splitStr2)[1]);
								}
								break;
							}else{
								System.err.println("没有匹配到数据!!!");
							}
						}catch(Exception e){
							System.err.println("pElement进入catch异常,没有匹配到数据!!!");
						}
					}
				}else{
					String resultCont = driver.findElement(By.cssSelector("#MapInfo > #txtPanel")).getText();
					System.err.println(resultCont);
//					compImportUpdate.setResultCont(resultCont);
					
					if(isNull){
						existData.setCityId(cityId);
						existData.setCompName(compName);
						existDataList.add(existData);
					}else{
						nullData.setCityId(cityId);
						nullData.setCompName(compName);
						nullDataList.add(nullData);
					}
				}

				int total = 0;
				int existDataListSize = 0;
				int nullDataListSize = 0;
				if(existDataList!=null && existDataList.size()>0){
					existDataListSize = existDataList.size();
				}
				if(nullDataList!=null && nullDataList.size()>0){
					nullDataListSize = nullDataList.size();
				}
				total = existDataListSize + nullDataListSize;
				System.out.println("total{{}}==>" + total);
				System.out.println("existDataListSize{{}}==>" + existDataListSize);
				System.out.println("nullDataListSize{{}}==>" + nullDataListSize);
				System.out.println("现爬取量为:" + total + "，最大可爬取量为:" + pageSize);
				if(total==pageSize){
					if(existDataList!=null && existDataList.size()>0){
						//根据地市ID和企业名称批量更新企业导入表的经纬度数据
						compImportService.batchUpdateCompImportByCityId(existDataList);
					}
					if(nullDataList!=null && nullDataList.size()>0){
						//根据地市ID和企业名称批量更新爬取企业导入表数据表设置is_update_lng_lat字段为T(意指在百度拾取坐标系统网站没有搜索到坐标数据)
						compImportService.batchUpdateCompImportForUpdateLngLatNotMatchByCityId(nullDataList);
					}
				}
				
				System.out.println("休眠3000毫秒......");
				try{
					Thread.sleep(3000);
				}catch(Exception e){
				}
				System.out.println("已休眠3000毫秒,继续查询数据==>");
//				driver.quit();
			}
		}else{
			System.out.println("要爬取企业导入表数据为空，系统自动停止!!!");
			System.exit(0);;
		}
	}
	
	/**
	 * 通过百度拾取坐标系统获取某酒店/会所坐标数据信息
	 */
	private static void testBaiduHotelPointData(){
		String cityName = "广州";
		String hotelName = "广东省揭阳工艺品进出口公司";
		// 1、开启个浏览器并且输入链接
		WebDriver driver = WebDriverUtils.getChromeDriver("http://api.map.baidu.com/lbsapi/getpoint/index.html");
		System.out.println("搜素名称{{}}==>" + hotelName);
		
		// 2、向百度拾取坐标系统输入框输入需要查询的值
		WebDriverUtils.inputStrByJS(driver, "localvalue", hotelName);
		
		JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("showPop()");

        // 休息5秒，加载数据
 		try {
 			Thread.sleep(5000);
 		} catch (InterruptedException e) {
 			e.printStackTrace();
 		}
 		
 		if("广州".equals(cityName)){
 			//广州
 			WebElement changeCityElement = driver.findElement(By.xpath("//*[@id=\"selCity\"]/tbody/tr[6]/td[2]/nobr[1]/a"));
 			WebDriverUtils.scrollToElementAndClick(changeCityElement, driver);
 		}else if("深圳".equals(cityName)){
	 		//深圳
 			WebElement changeCityElement = driver.findElement(By.xpath("//*[@id=\"selCity\"]/tbody/tr[6]/td[2]/nobr[15]/a"));
	 		WebDriverUtils.scrollToElementAndClick(changeCityElement, driver);
 		}

        // 休息5秒，加载数据
 		try {
 			Thread.sleep(5000);
 		} catch (InterruptedException e) {
 			e.printStackTrace();
 		}
		
		// 4、得到百度一下的按钮
		WebElement submitElement = driver.findElement(By.id("localsearch"));

		// 5、点击百度一下
		WebDriverUtils.scrollToElementAndClick(submitElement, driver);

		// 休息5秒，加载数据
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		// 6、右侧地图Info中div的 id 为 MapInfo 的 div 下面的所有 div
		List<WebElement> divElements = driver.findElements(By.cssSelector("#MapInfo > #txtPanel > ul"));
		
		if(divElements!=null && divElements.size()>0){
			for(int i = 0; i<divElements.size(); i++){
				// 7、找到搜索的第一个链接
				try{
					WebElement aElement = divElements.get(i).findElement(By.cssSelector("li > div > a"));
					String aTextName = aElement.getText();
					if(aElement!=null){
						if(aTextName.equals(hotelName)){
							System.out.println("hotelName{{}}==>" + hotelName);
						}else{
							System.out.println("aTextName{{}}==>" + aTextName);
						}
					}else{
						System.err.println("没有匹配到数据!!!");
					}
					WebElement pElement = divElements.get(i).findElement(By.cssSelector("li > div > p"));
					if(pElement!=null){
						String splitStr1 = "：";
						String splitStr2 = ",";
						String pTextName = pElement.getText();
						String[] pTexts = pElement.getText().split("\n");
//						System.out.println(pTextName);
						
						if(pTextName.contains("电话" + splitStr1)){
							System.out.println("电话号码{{}}==>" + pTexts[1].split(splitStr1)[1]);
							System.out.println("横坐标{{}}==>" + pTexts[2].split(splitStr1)[1].split(splitStr2)[0]);
							System.out.println("纵坐标{{}}==>" + pTexts[2].split(splitStr1)[1].split(splitStr2)[1]);
						}else{
							System.out.println("横坐标{{}}==>" + pTexts[1].split(splitStr1)[1].split(splitStr2)[0]);
							System.out.println("纵坐标{{}}==>" + pTexts[1].split(splitStr1)[1].split(splitStr2)[1]);
						}
					}else{
						System.err.println("没有匹配到数据!!!");
					}
				}catch(Exception e){
					System.err.println("进入catch异常,没有匹配到数据!!!");
				}
			}
		}else{
			System.err.println(driver.findElement(By.cssSelector("#MapInfo > #txtPanel")).getText());
		}
		driver.quit();
	}
	
	public static void main(String[] args){
		testBaiduHotelPointData();
	}
}